package com.xuecheng.orders.domain.jobhandler;

import com.xuecheng.orders.domain.model.entity.XcPayRecord;
import com.xuecheng.orders.domain.service.XcOrdersService;
import com.xuecheng.orders.domain.service.XcPayRecordService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-16  10:22
 */
@Slf4j
@Component
public class OrderRepeatJob {

    @Autowired
    private XcPayRecordService xcPayRecordService;


    @XxlJob(value = "orderRepeatJob")
    public void orderRepeatJob(){
        log.info("执行订单重复支付回调任务调度");
        // 取出cpu核心数作为一次处理数据的条数
        Integer processors = Runtime.getRuntime().availableProcessors();
        process(processors);
    }

    private void process(Integer processors) {
        try {
            // 取出前一天出现的重复支付
            List<XcPayRecord> xcPayRecords = xcPayRecordService.getPayRepeatTask();
            Set<XcPayRecord> records = new HashSet<>(xcPayRecords);

            ExecutorService executorService = Executors.newFixedThreadPool(processors);
            CountDownLatch countDownLatch = new CountDownLatch(records.size());
            // 调用退款方法
            for (XcPayRecord record : records) {
                try {
                    executorService.submit(() -> {
                        xcPayRecordService.returnPay(record);
                    });
                } catch (Exception e){
                    log.error("任务调度出错:{}", e.getMessage());
                } finally {
                    countDownLatch.countDown();
                }
                countDownLatch.await(30, TimeUnit.SECONDS);

            }
            //等待,给一个充裕的超时时间,防止无限等待，到达超时时间还没有处理完成则结束任务
            countDownLatch.await(30, TimeUnit.SECONDS);
            log.info("执行消息任务结束");
        } catch (Exception e){
            log.error("任务调度出错:{}", e.getMessage());
        }
    }

}
